package cn.edu.lzzy.mypractices.web.chapter;

import cn.edu.lzzy.mypractices.constant.ApiConstant;
import cn.edu.lzzy.mypractices.constant.Messages;
import cn.edu.lzzy.mypractices.entity.Chapter;
import cn.edu.lzzy.mypractices.entity.Option;
import cn.edu.lzzy.mypractices.entity.Question;
import cn.edu.lzzy.mypractices.service.ChapterService;
import cn.edu.lzzy.mypractices.service.QuestionService;
import cn.edu.lzzy.mypractices.util.StringUtils;
import cn.edu.lzzy.mypractices.web.model.ApiResult;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Api(tags = "课程题目相关业务")
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_QUESTION_ROOT)
public class QuestionApiController {
    private final ChapterService chapterService;
    private final QuestionService questionService;

    public QuestionApiController(ChapterService chapterService, QuestionService questionService) {
        this.chapterService = chapterService;
        this.questionService = questionService;
    }

    @ApiOperation("查询章节下的所有题目")
    @GetMapping(ApiConstant.ROUTE_QUESTION_CHAPTER)
    public ApiResult getAllQuestionByChapter(@RequestParam String token, @RequestParam UUID chapterId) {
        List<ApiResult.VmQuestion> questionList = new ArrayList<>(); // 性能 == 不要钱
        questionService.getAllByChapter(chapterId).forEach(o -> questionList.add(ApiResult.VmQuestion.create(o, false)));
        return new ApiResult(true, questionService.count(chapterId) + "", questionList);
    }

    @ApiOperation("分页查询所有题目")
    @GetMapping(ApiConstant.ROUTE_QUESTION_CHAPTER_PAGE)
    public ApiResult getPagedQuestions(@RequestParam String token, @RequestParam UUID chapterId, @RequestParam int page, @RequestParam int size) {
        List<ApiResult.VmQuestion> questions = new ArrayList<>();
        questionService.getAllByChapter(chapterId, page, size).forEach(question -> questions.add(ApiResult.VmQuestion.create(question, false)));
        return new ApiResult(true, questionService.count(chapterId) + "", questions);
    }

    private ApiResult questionAddOrUpdate(String questionId, String chapterId, JSONObject json, boolean isUpdate) {
        String token = json.getString(ApiConstant.KEY_TOKEN);

        int type = json.getInteger(ApiConstant.KEY_QUESTION_TYPE);
        String content = json.getString(ApiConstant.KEY_QUESTION_CONTENT);
        String analysis = json.getString(ApiConstant.KEY_QUESTION_ANALYSIS);
        int ordinal = json.getInteger(ApiConstant.KEY_QUESTION_ORDINAL);

        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(analysis) || StringUtils.isEmpty(chapterId) || (isUpdate && questionId == null)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        // 查询章节列表检查是否有该章节
        Chapter chapter = chapterService.getByChapterId(UUID.fromString(chapterId));
        if (chapter == null) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), null);
        }

        Question question;
        boolean create = questionId == null;
        if (create) {
            question = new Question();
            question.setChapter(chapter);
        } else {
            //更新
            //根据id获取数据库的指定问题
            question = questionService.getByQuestionId(UUID.fromString(questionId));
            if (question == null) {
                return new ApiResult(false, Messages.WRONG_ID.toString(), null);
            }
        }

        question.setType(type);
        question.setContent(content);
        question.setAnalysis(analysis);
        question.setOrdinal(ordinal);

        if (create) {
            Question created = questionService.addQuestion(question);
            return new ApiResult(true, "", ApiResult.VmQuestion.create(created, true));
        } else {
            Question updated = questionService.updateQuestion(question);
            if (updated == null) {
                return new ApiResult(false, Messages.NO_PERMISSION.toString(), null);
            }
            return new ApiResult(true, "", ApiResult.VmQuestion.create(updated, false));
        }
    }

    @ApiOperation("新增题目")
    @PostMapping(value = ApiConstant.ROUTE_QUESTION_ADD, produces = ApiConstant.API_PRODUCES)
    public ApiResult addQuestion(@RequestParam String chapterId, @RequestBody JSONObject question) {
        return questionAddOrUpdate(null, chapterId, question, false);
    }

    @ApiOperation("更新指定题目")
    @PostMapping(value = ApiConstant.ROUTE_QUESTION_PUT, produces = ApiConstant.API_PRODUCES)
    public ApiResult updateQuestion(
            @ApiParam(value = "chapter_id", required = true) @RequestParam String chapterId,
            @ApiParam(value = "question_id", required = true) @RequestParam String questionId,
            @RequestBody JSONObject question) {
        return questionAddOrUpdate(questionId, chapterId, question, true);
    }

    // 同上
    @ApiOperation("删除题目")
    @PostMapping(value = ApiConstant.ROUTE_QUESTION_DELETE, produces = ApiConstant.API_PRODUCES)
    public ApiResult deleteQuestion(@RequestBody JSONObject json) {
        String token = json.getString(ApiConstant.KEY_TOKEN);
        String questionId = json.getString(ApiConstant.KEY_QUESTION_ID);

        if (StringUtils.isEmpty(token) && StringUtils.isEmpty(questionId)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        try {
            UUID questionUUID = UUID.fromString(questionId);

            Messages msg = questionService.removeQuestion(questionUUID, token);
            return new ApiResult(msg == Messages.SUCCESS, msg.toString(), null);
        } catch (Exception e) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), e.getMessage());
        }
    }

    @ApiOperation("添加题目选项")
    @PostMapping(value = ApiConstant.ROUTE_QUESTION_OPTION_ADD, produces = ApiConstant.API_PRODUCES)
    public ApiResult addOption(@RequestParam String questionId, @RequestBody JSONObject json) {
        String content = json.getString(ApiConstant.KEY_OPTION_CONTENT);
        String label = json.getString(ApiConstant.KEY_OPTION_LABEL);
        boolean isAnswer = json.getBoolean(ApiConstant.KEY_OPTION_IS_ANSWER);

        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(label) || StringUtils.isEmpty(questionId)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        Question question = questionService.getByQuestionId(UUID.fromString(questionId));
        if (question == null) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), null);
        }

        Option option = new Option();

        option.setQuestion(question);
        option.setContent(content);
        option.setLabel(label);
        option.setAnswer(isAnswer);

        Option added = questionService.addOption(option);
        return new ApiResult(true, Messages.SUCCESS.toString(), ApiResult.VmOption.create(added));
    }

    @ApiOperation("删除题目选项")
    @PostMapping(value = ApiConstant.ROUTE_QUESTION_OPTION_DELETE, produces = ApiConstant.API_PRODUCES)
    public ApiResult removeOption(@RequestBody JSONObject json) {
        String token = json.getString(ApiConstant.KEY_TOKEN);
        String optionId = json.getString(ApiConstant.KEY_QUESTION_OPTION_ID);

        if (StringUtils.isEmpty(token) && StringUtils.isEmpty(optionId)) {
            return new ApiResult(false, Messages.INCOMPLETE_INFO.toString(), null);
        }

        try {
            UUID optUUID = UUID.fromString(optionId);
            Messages msg = questionService.removeOption(optUUID, token);
            return new ApiResult(msg == Messages.SUCCESS, msg.toString(), null);
        } catch (Exception e) {
            return new ApiResult(false, Messages.WRONG_ID.toString(), e.getMessage());
        }
    }
}
